#include "createtask.h"
#include "ui_createtask.h"
#include "taskitem.h"
#include <QDebug>




CreateTask::CreateTask(int taskId,QWidget *parent) :
    QWidget(parent),
    ui(new Ui::CreateTask),
    m_hasSubTask(false),
    m_taskId(taskId)

{
    ui->setupUi(this);
    // 设置关闭窗口后不退出程序
    setAttribute(Qt::WA_QuitOnClose, false);
    setAttribute(Qt::WA_DeleteOnClose,true);


    // 禁止调整窗口大小
    setFixedSize(this->width(), this->height());
    this->setWindowTitle("创建任务");
    this->setWindowIcon(QIcon(":/pics/trayico"));
    //初始化具有自定义数据的comboBox
        //QMap自动根据 key排序
    QVector<QPair<QString, int>> sortItem;
    sortItem.push_back(QPair<QString, int>("请选择",-1));
    sortItem.push_back(QPair<QString, int>("重要紧急",0));
    sortItem.push_back(QPair<QString, int>("重要不紧急",1));
    sortItem.push_back(QPair<QString, int>("不重要不紧急",2));
    sortItem.push_back(QPair<QString, int>("不重要紧急",3));

    ui->sortcombo->clear();
    foreach(auto &p,sortItem)
        ui->sortcombo->addItem(p.first,p.second);


    // 设置添加按钮
    QSize size(15,15);
    m_pix_add = QPixmap(":/pics/add.png").scaled(size,  Qt::IgnoreAspectRatio, Qt::SmoothTransformation);
    m_pix_delete = QPixmap(":/pics/delete.png").scaled(size,  Qt::IgnoreAspectRatio, Qt::SmoothTransformation);

    initSubTaskTable();

    // 设置模式
    if (taskId >= 0)
    {
        m_model = model::EDIT;
        this->setWindowTitle("编辑任务");

    }

    else
        m_model = model::CREATE;


}

CreateTask::~CreateTask()
{
    delete ui;
}

void CreateTask::initSubTaskTable()
{

    ui->subTaskTable->clear();
    ui->subTaskTable->setColumnCount(5);
    // 隐藏行号
    QHeaderView *header = ui->subTaskTable->verticalHeader();
    header->setHidden(true);
//    header->setSectionResizeMode(QHeaderView::Stretch);
    ui->subTaskTable->setColumnHidden(ID, true);
    ui->subTaskTable->setColumnWidth(NAME, 100);
    ui->subTaskTable->setColumnWidth(TOMATO, 50);
    ui->subTaskTable->setColumnWidth(ADD, 50);
    ui->subTaskTable->setColumnWidth(DELETE, 35);

    // 以行为单位选中
    ui->subTaskTable->setSelectionBehavior ( QAbstractItemView::SelectRows);
//    ui->subTaskTable->setSelectionMode ( QAbstractItemView::SingleSelection);
    ui->subTaskTable->setSelectionMode ( QAbstractItemView::NoSelection);

    ui->subTaskTable->setFont(QFont("宋体"));

    //设置表格中每一行的表头
    ui->subTaskTable->setHorizontalHeaderLabels(QStringList() << "ID" << "任务名" << "番茄数" <<"添加"<< "删除");
    //设置表格数据区内的所有单元格都不允许编辑
    ui->subTaskTable->setEditTriggers(QAbstractItemView::NoEditTriggers);

    ui->subTaskTable->setShowGrid(true);
    ui->subTaskTable->setWindowFlags(Qt::FramelessWindowHint);

    addSubTask(-1);

    // 绑定事件
    connect(ui->subTaskTable, &QTableWidget::cellClicked,
            [=](int row, int column)
            {

                qDebug() << "click row " <<row << " column " << column << endl;

               if (column == CreateTask::DELETE)
               {
                   QTableWidgetItem *item = ui->subTaskTable->item(row, CreateTask::NAME);
                   int ret = QMessageBox::question(this,
                    "提示", "是否删除子任务 "+item->text(), "确定", "取消"
                                                   );
                   switch(ret)
                   {
                     case 0:
                       qDebug() << "click 确定";

                       ui->subTaskTable->removeRow(row);
                       if (ui->subTaskTable->rowCount() == 0)
                       {
                           taskTomatoEditDisable(false);
                           m_hasSubTask = false;
                           addSubTask(-1);
                       }
                       // 更新番茄总数
                       updateTaskTomato();
                       break;
                     case 1:
                       qDebug() << "click 取消";
                       break;
                   }
               } else if (column == CreateTask::ADD){
                   AddSubTaskW *add_sub_task = new AddSubTaskW(row+1);
                   connect(add_sub_task, &AddSubTaskW::sendNewSubTask, this, &CreateTask::addSubTaskFromW);
                   add_sub_task->setAttribute(Qt::WA_DeleteOnClose);
                   add_sub_task->exec();
//                    addSubTask(row);
               }


            }
            );

}

void CreateTask::updateTaskTomato()
{
    if (m_hasSubTask)
    {
        int count = 0;
        for (int i=0; i<ui->subTaskTable->rowCount(); ++i)
        {
            count += ui->subTaskTable->item(i, TOMATO)->text().toInt();

        }
        ui->tomatoTotal->setValue(count);
    }
}

void CreateTask::fillContent(const taskItem &task)
{
    ui->taskNameInput->setText(task.m_taskName);
    ui->sortcombo->setCurrentIndex(task.m_sort+1);
    ui->eachDayTomato->setValue(task.m_eachDayTomatoes);
    if (task.m_days < 0)
        ui->isEveryDay->setChecked(true);
    else
        ui->isEveryDay->setChecked(false);

    ui->tomatoTotal->setValue(task.m_tomatoesTotal);

    ui->subTaskTable->setRowCount(0);

    ui->describTextEdit->setText(task.m_describe);

    m_tomatoAchieveToday = task.m_todayAchieveTomato;
    m_tomatoAchieveTotal = task.m_tomatoesAchieveTotal;

    int row=0;
    if (task.m_subTaskMap.size() > 0)
    {
        for (auto i=task.m_subTaskMap.constBegin(); i != task.m_subTaskMap.constEnd(); ++i){
            if (!i->name.isEmpty()){
                loadSubTasks(row++, *i);
            }
        }
    } else
        addSubTask(-1);


}

void CreateTask::loadSubTasks(int newRow, const subTask &subtask)
{


    ui->subTaskTable->insertRow(newRow);
    ui->subTaskTable->setRowHeight(newRow, 15);

    QTableWidgetItem * widget_item;


    // ID
    widget_item = new QTableWidgetItem(QString("%1").arg(subtask.id));
    widget_item->setToolTip("子任务ID");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,ID, widget_item);


    // taskName
    widget_item = new QTableWidgetItem(QString(subtask.name));
    widget_item->setToolTip("子任务名");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,NAME, widget_item);

    // tomatoes
    widget_item = new QTableWidgetItem(QString("%1").arg(subtask.tomato));
    widget_item->setToolTip("子任务番茄总数");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,TOMATO, widget_item);

    // add button
    QLabel *addBtn = new QLabel();
    addBtn->setToolTip("在下方插入行");
    // 设置鼠标在label上的形状
    addBtn->setCursor(Qt::PointingHandCursor);
    addBtn->setPixmap(m_pix_add);
    addBtn->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setCellWidget(newRow, ADD, addBtn);

    // 删除按钮

    QLabel *trash = new QLabel();
    trash->setToolTip("删除此行");
    // 设置鼠标在label上的形状
    trash->setCursor(Qt::PointingHandCursor);
    trash->setPixmap(m_pix_delete);
    trash->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setCellWidget(newRow, DELETE, trash);

    // 更新番茄总数
    updateTaskTomato();
}

void CreateTask::addSubTask(int row)
{
//    if (hasSubTask == false) taskTomatoEditDisable(true);
//    hasSubTask = true;
    int newRow = row + 1;

    ui->subTaskTable->insertRow(newRow);
    ui->subTaskTable->setRowHeight(newRow, 15);

    QTableWidgetItem * widget_item;


    // ID
    widget_item = new QTableWidgetItem(QString("%1").arg(m_subtask_tmp_id--));
    widget_item->setToolTip("子任务ID");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,ID, widget_item);

    // taskName
    widget_item = new QTableWidgetItem(QString(""));
    widget_item->setToolTip("子任务名");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,NAME, widget_item);

    // tomatoes

    widget_item = new QTableWidgetItem(QString(""));
    widget_item->setToolTip("子任务番茄总数");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,TOMATO, widget_item);

    // add button
    QLabel *addBtn = new QLabel();
    addBtn->setToolTip("在下方插入行");
    // 设置鼠标在label上的形状
    addBtn->setCursor(Qt::PointingHandCursor);
    addBtn->setPixmap(m_pix_add);
    addBtn->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setCellWidget(newRow, ADD, addBtn);

    // 删除按钮

    QLabel *trash = new QLabel();
    trash->setToolTip("删除此行");
    // 设置鼠标在label上的形状
    trash->setCursor(Qt::PointingHandCursor);
    trash->setPixmap(m_pix_delete);
    trash->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setCellWidget(newRow, DELETE, trash);

    // 更新番茄总数
    updateTaskTomato();
}

void CreateTask::on_createButton_clicked()
{
    QString taskName = this->ui->taskNameInput->text();
    if (taskName.isEmpty()){
        QMessageBox::warning(this, "提示","任务名不能为空!", "确定");
        return ;
    }

    int sort = this->ui->sortcombo->currentData().toInt();

    if (sort == -1)
    {
        QMessageBox::warning(this, "提示","请选择任务分类!", "确定");
        return ;
    }

    int eachDayTomato = this->ui->eachDayTomato->value();
    int tomatoTotal = this->ui->tomatoTotal->value();

    if (!ui->isEveryDay->isChecked() && tomatoTotal < eachDayTomato){
        QMessageBox::warning(this, "提示","番茄总数不能小于每日番茄数!", "确定");
        return ;
    }

    int dayCount = this->ui->isEveryDay->checkState();
    if (dayCount == Qt::Checked) dayCount = -1;

    QString describe = this->ui->describTextEdit->toPlainText();
    qDebug() << "taskName "<<taskName<<"\nsort " << sort
             <<"\n番茄数 "<<eachDayTomato<<"\n天数 "<<dayCount<<endl;


    // 修改数据库中数据
    taskItem *taskitem;
    if (m_model == model::CREATE)
    {
         taskitem = new taskItem(
                    taskName,
                    sort,
                    eachDayTomato,
                    tomatoTotal,
                    dayCount,
                    describe
                    );

        for(int i=0; i<this->ui->subTaskTable->rowCount(); ++i)
        {
            int id = ui->subTaskTable->item(i, ID)->text().toInt();
            QString name = ui->subTaskTable->item(i, NAME)->text();
            if (name.isEmpty()) continue;
            int tomato = ui->subTaskTable->item(i, TOMATO)->text().toInt();
            taskitem->addSubTask(id, name, tomato);
        }


        taskitem->insertdb(Ndb::query);
        emit this->TableAddTask(*taskitem);
    } else
    {
        taskitem = new taskItem(
                    taskName,
                    sort,
                    eachDayTomato,
                    tomatoTotal,
                    dayCount,
                    describe
                    );
        taskitem->m_tomatoesAchieveTotal = m_tomatoAchieveTotal;
        taskitem->m_todayAchieveTomato = m_tomatoAchieveToday;

        for(int i=0; i<this->ui->subTaskTable->rowCount(); ++i){
            int id = ui->subTaskTable->item(i, ID)->text().toInt();
            QString name = ui->subTaskTable->item(i, NAME)->text();
            if (name.isEmpty()) continue;
            int tomato = ui->subTaskTable->item(i, TOMATO)->text().toInt();
            taskitem->addSubTask(id, name, tomato);
        }
        taskitem->m_id = m_taskId;
        taskitem->updatedb(Ndb::query);
        emit this->TableUpdateTask(*taskitem);
        qDebug() << "create task emit update task";
    }

    // 修改对应分类显示项目


    this->close();

}

void CreateTask::on_pushButton_clicked()
{

}


bool CreateTask::checkSubTaskExist(subTask &subtask)
{
    for(int r=0; r<ui->subTaskTable->rowCount(); ++r)
    {
        if (ui->subTaskTable->item(r, CreateTask::NAME)->text() == subtask.name)
        {
            return true;
        }
    }
    return false;
}

void CreateTask::taskTomatoEditDisable(bool flag)
{
    ui->tomatoTotal->setDisabled(flag);
}

void CreateTask::addSubTaskFromW(int newRow, subTask subtask)
{

    if (m_hasSubTask == false) taskTomatoEditDisable(true);
    m_hasSubTask = true;

    if (checkSubTaskExist(subtask))
    {
        QMessageBox::warning(this, "提示","子任务名已存在!","确定");
        return ;
    }
    if (newRow >= 1 && ui->subTaskTable->item(newRow-1, NAME)->text().isEmpty()){
        newRow -= 1;
        ui->subTaskTable->setRowHeight(newRow, 15);
    }

    else{
        ui->subTaskTable->insertRow(newRow);
        ui->subTaskTable->setRowHeight(newRow, 15);
    }


    QTableWidgetItem * widget_item;



    // ID
    widget_item = new QTableWidgetItem(QString("%1").arg(m_subtask_tmp_id--));
    widget_item->setToolTip("子任务ID");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,ID, widget_item);

    // name

    widget_item = new QTableWidgetItem(QString(subtask.name));
    widget_item->setToolTip(subtask.describe);
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,NAME, widget_item);



    // tomatoes

    widget_item = new QTableWidgetItem(QString("%1").arg(subtask.tomato));
    widget_item->setToolTip("子任务/步骤 所需的番茄总数");
    widget_item->setTextAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setItem(newRow,TOMATO, widget_item);

    // add button
    QLabel *addBtn = new QLabel();
    addBtn->setToolTip("在下方插入子任务");
    // 设置鼠标在label上的形状
    addBtn->setCursor(Qt::PointingHandCursor);
    addBtn->setPixmap(m_pix_add);
    addBtn->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setCellWidget(newRow, ADD, addBtn);

    // 删除按钮

    QLabel *trash = new QLabel();
    trash->setToolTip("删除子任务");
    // 设置鼠标在label上的形状
    trash->setCursor(Qt::PointingHandCursor);
    trash->setPixmap(m_pix_delete);
    trash->setAlignment(Qt::AlignHCenter | Qt::AlignVCenter);
    ui->subTaskTable->setCellWidget(newRow, DELETE, trash);

    // 更新番茄总数
    updateTaskTomato();


}

void CreateTask::on_isEveryDay_stateChanged(int arg1)
{
    if (arg1 > 0)
    {
        ui->tomatoTotal->setDisabled(true);

    } else if (arg1 == 0 && !m_hasSubTask)
    {
        ui->tomatoTotal->setDisabled(false);
    }
    qDebug() << ui->isEveryDay->checkState();

}
